
/**
 * Module dependencies.
 */

var logger = require('koa-logger');
var serve = require('koa-static');
const koaBody = require('koa-body');
var router = require('koa-router')(); 
var koa = require('koa');
var fs = require('fs');
var app = new koa();
var path = require('path');

// log requests
//app.use(logger());
app.use(koaBody({multipart:true}));////使用这个参数 koa-body 解析的时候才会解析你的form
router.get('/',async(ctx,next)=>{
	await next();
  if (ctx.body || !ctx.idempotent) return;
  ctx.redirect('/404.html');
});

// serve files from ./public

app.use(serve(path.join(__dirname, '/public')));

// handle uploa
//上传文件
router.post('/upload',async(ctx,next)=>{
		console.log('_dirname：',__dirname);
		console.log('path:',path);
		console.log('param:',ctx.request.body)
		var files=ctx.request.body.files.upfile;
		console.log(files);
		if(files.length>0){
			for(var item in files){
				var tmpath= files[item]['path'];//获取上传的文件路径
				var tmparr =files[item]['name'].split('.');//拆分文件
				var ext ='.'+tmparr[tmparr.length-1];//后缀
				var newpath =path.join('temp', parseInt(Math.random()*100) + Date.parse(new Date()).toString() + ext);//新文件名称
				var stream = fs.createWriteStream(newpath);//创建一个可写流
				fs.createReadStream(tmpath).pipe(stream);//可读流通过管道写入可写流
			}
		}else{
			//当files为对象时即只有一个文件被上传
			var tmpath= files['path'];
			var tmparr =files['name'].split('.');
			var ext ='.'+tmparr[tmparr.length-1];
			var newpath =path.join('temp', parseInt(Math.random()*100) + Date.parse(new Date()).toString() + ext);
			console.log(tmpath);
			console.log(newpath);
			var stream = fs.createWriteStream(newpath);//创建一个可写流
			fs.createReadStream(tmpath).pipe(stream);//可读流通过管道写入可写流
		}
		//设置上传成功后页面提示
		ctx.request.acceptsCharsets("utf-8");
		ctx.cookies.set("tip",escape("文件上传成功！"),{maxAge:3000,expires:Date.now()+3000});
		//console.log(this.cookies.get("tip"));
		//上传成功后的页面跳转
		ctx.redirect('/');
	
})

router.get('/hello',async(ctx,next)=>{
	ctx.body = "<h1>hello</h1>";
})

app.use(router.routes());

// listen

app.listen(8888);
